package com.example.android.debuggermenu;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Vector;

import clientcore.GameState;
import clientcore.Message;

import com.example.android.debuggermenu.Friends.FriendRowAdapter;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.util.SparseBooleanArray;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CheckedTextView;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

public class Chat extends ListActivity {
	private Context mContext = this;
	private HashMap<String, Boolean> buds;
	private List<String> onlineFriends = new ArrayList<String>();
	private HashMap<String, Boolean> itemsChecked;
	private AlertDialog chatDialog;
	private AlertDialog.Builder builder;
	private Integer numOfChats = 0, numOfInvites = 0;
	private Intent messageIntent;
	private ArrayList<String> namesToSend;
	
	
    public void onCreate(Bundle savedInstanceState) {
    	super.onCreate(savedInstanceState);
        
    	/*
        super.onCreate(savedInstanceState);
        final ListView listView = getListView();
        
        //final Button send = (Button) findViewById(R.id.sendbutton);
        //listView.addFooterView(send);
        setContentView(R.layout.chat_list);
           
        listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
        listView.setItemsCanFocus(false);
        
        final RelativeLayout layout = (RelativeLayout) findViewById(R.id.chat_rl);
        final Button send = new Button(this);
        
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.FILL_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
        params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
        send.setLayoutParams(params);
        layout.addView(send);
        send.bringToFront();
        send.setText("Send");
        
        send.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				SparseBooleanArray checked = listView.getCheckedItemPositions();
	    		if (checked.size() == 0) {
	    			Toast.makeText(mContext, "No friends selected", Toast.LENGTH_SHORT).show();
	    		} else {
	    			ArrayList<String> namesToSend = new ArrayList<String>();
	        		
	    			Toast.makeText(mContext, checked.size() + " items selected", Toast.LENGTH_SHORT).show();
	    			
	        		int j = 0;
	        		for (int i = 0; i < onlineFriends.size(); i++) {
	        			if (checked.indexOfKey(j) == (i+1)) {
	        				namesToSend.add(onlineFriends.get(i));
	        				j++;
	        			}
	        			if (j >= checked.size()) {
	        				break;
	        			}
	        		}
	    		}
			}
        });
        */
        

    }
    
    public void onResume() {
    	super.onResume();
    	new loadOnlineBuddies().execute();
    }
    
    public void onPause() {
    	super.onPause();
    	onlineFriends.clear();
    }
    
    public void chatDialog(ListView listView) {
    	
    	View chatDialogBox = this.getLayoutInflater().inflate(R.layout.mult_chat_dialog, (ViewGroup)findViewById(R.id.mult_chat_dialog));
    	builder = new AlertDialog.Builder(this);
    	builder.setView(chatDialogBox);
    	
    	ScrollView sv = (ScrollView) chatDialogBox.findViewById(R.id.chat2_scrollview);
        LinearLayout ll = (LinearLayout) chatDialogBox.findViewById(R.id.linear_scroll);
        final Button chatSend = (Button) chatDialogBox.findViewById(R.id.chat2_sendButton);
        final Button chatCancel = (Button) chatDialogBox.findViewById(R.id.chat2_cancelButton);
		final EditText response = (EditText) chatDialogBox.findViewById(R.id.chat2_edit_txt);
        
		SparseBooleanArray checked = listView.getCheckedItemPositions();
		if (checked.size() == 0) {
			Toast.makeText(mContext, "No friends selected", Toast.LENGTH_LONG).show();
		} else {
			namesToSend = new ArrayList<String>();			
    		int j = 0;
    		for (int i = 0; i < onlineFriends.size(); i++) {
    			if (checked.indexOfKey(i) < 0) {
    				//index does not represent one of our online friends; increment
    			} else {
    				namesToSend.add(onlineFriends.get(i));
    			}
    		}
    		
    		for (int i = 0; i < namesToSend.size(); i++) {
            	TextView tv = new TextView(this);
            	tv.setText(namesToSend.get(i));
            	tv.setTextSize(20);
            	tv.setGravity(Gravity.CENTER);
            	ll.addView(tv);
            }
    		checked.clear();
    		
    		chatSend.setOnClickListener(new View.OnClickListener() {
    			public void onClick(View v) {
    				String message = response.getText().toString();
    				
    				for (int i = 0; i < namesToSend.size(); i++) {
    					GameState.sendPrivateChat(namesToSend.get(i), message);
    				}
    				Toast.makeText(mContext, namesToSend.size() + " messages sent!", Toast.LENGTH_LONG).show();
    				chatDialog.dismiss();
    			}
    		});
    		    
    		chatCancel.setOnClickListener(new View.OnClickListener() {
    			public void onClick(View v) {
    				chatDialog.dismiss();
    				
    			}
    		});
    		chatDialog = builder.create();
    		chatDialog.show();
		}
	}
        
        
        
    	
    
    public boolean onCreateOptionsMenu(Menu menu) {
    	MenuInflater inflater = getMenuInflater();
    	inflater.inflate(R.menu.chat_menu, menu);
    	return true;
    }
    
    public boolean onOptionsItemSelected(MenuItem item) {
    	if (item.getItemId() == R.id.messagelist) {
    		messageIntent = new Intent(this, MessageList.class);
    		startActivity(messageIntent);
    		return true;
    	}
		return false;
    }
    
    /*
    public void onListItemClick(ListView parent, View v, int position, long id) {
    	chatRow = (CheckBox) findViewById(R.id.chat_check_box);
    	String name = (String) getListView().getItemAtPosition(position);
    	
    	if (chatRow.isChecked()) {
    		chatRow.setChecked(false);
    		itemsChecked.remove(name);
    	} else {
    		chatRow.setChecked(true);
        	itemsChecked.put(name, true);
    	}
    }
    */
    
    private class loadOnlineBuddies extends AsyncTask<Void, Void, HashMap<String, Boolean>> {
		private ProgressDialog dialog;
 
		protected void onPreExecute() {
			Log.d("LoadBuddies", "begin onPreExecute");
			dialog = new ProgressDialog(mContext);
			dialog.setMessage("Loading...");
			dialog.setCancelable(false); 
			dialog.show();
		}
 
		@Override
		protected HashMap<String, Boolean> doInBackground(Void... arg0) {
			Log.d("LoadOnlineBuddies", "begin doInBackground");
			
			Vector<Message> chatMessages = GameState.updatePrivateChats();
			Log.d("getChats", "connection made");
			for(Message m : chatMessages) {
		      	Log.d("CHATS", "SENDER: " + m.getSender() + " MESSAGE: " + m.getText());
		      	GameState.addMessage(m);
		    }
			numOfChats = chatMessages.size();
			chatMessages.clear();
			
			Vector<Message> inviteMessages = GameState.updateBuddyInvites();
			Log.d("LoadOnlineBuddies", "connection made for invites");
			for(Message m : inviteMessages) {
	        	Log.d("BUDDY INVITES", "SENDER: " + m.getSender() + " MESSAGE: " + m.getText());
	        	GameState.addInvite(m);
	        }
			numOfInvites = inviteMessages.size();
			inviteMessages.clear();
			
            buds = GameState.getBuddies();
            if(buds != null) {
    		    for(String name : buds.keySet()) {
    		    	Log.d("Friends", name + " " + (buds.get(name)? "online" : "offline"));
    		    	if (buds.get(name) == true) {
    		    		onlineFriends.add(name);
    		    	}
    		    }
            }
			return buds;
		}
 
		protected void onPostExecute(HashMap<String, Boolean> result) {
			Log.d("LoadOnlineBuddies", "begin onPostExecute");
			if (numOfChats > 0) {
				Toast.makeText(mContext, numOfChats + " new messages!", Toast.LENGTH_LONG).show();
			}
			if (numOfInvites > 0) {
				Toast.makeText(mContext, numOfInvites + " new invites!", Toast.LENGTH_LONG).show();
			}
			setContentView(R.layout.chat_list);
			
			final ListView listView = getListView();
	        
	        final RelativeLayout layout = (RelativeLayout) findViewById(R.id.chat_rl);
	        final Button send = new Button(mContext);
	        
	        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.FILL_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
	        params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
	        send.setLayoutParams(params);
	        send.bringToFront();
	        send.setText("Send");
	        layout.addView(send);
	        
	        listView.setItemsCanFocus(false);
	        listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
	        
	        send.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					chatDialog(listView);
				}
	        });
			
			
			setListAdapter(new ArrayAdapter<String>(mContext, android.R.layout.simple_list_item_multiple_choice, onlineFriends));
			dialog.dismiss();
		}
	}
    
}
